package com.blockchain.console.service.financial.achieve;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import com.blockchain.common.enums.CoinType;
import com.blockchain.common.enums.IsPass;
import com.blockchain.common.enums.PlatformFundType;
import com.blockchain.common.enums.PtXlbType;
import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.financial.PtzjManage;
import com.blockchain.console.service.financial.entity.Ptzjgl;
import com.blockchain.console.service.financial.entity.PtzjglRecord;
import com.blockchain.console.service.financial.entity.TtQbEntity;
import com.blockchain.console.service.financial.query.PtzjglRecordQuery;
import com.blockchain.console.servlets.util.BtcUtil;
import com.blockchain.console.servlets.util.EthereumUtil;
import com.blockchain.console.servlets.util.NEOUtil;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.util.MyCrypt;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.variables.P2PConst;

public class PtzjManageImpl extends AbstractFinancialService implements PtzjManage {

	public static class PlatformFundFactory implements ServiceFactory<PtzjManage> {

		@Override
		public PtzjManage newInstance(ServiceResource serviceResource) {
			return new PtzjManageImpl(serviceResource);
		}
	}

	public PtzjManageImpl(ServiceResource serviceResource) {
		super(serviceResource);

	}

	public Ptzjgl getPlatFormFundInfo() throws Throwable {
		Ptzjgl platformFund = new Ptzjgl();
		try (Connection conn = getConnection()) {
			try (PreparedStatement pst = conn.prepareStatement("SELECT F01, F02, F03,NOW() FROM T7013")) {
				try (ResultSet rst = pst.executeQuery()) {
					if (rst.next()) {
						platformFund.platformAmount = rst.getBigDecimal(1);
						platformFund.totalIncome = rst.getBigDecimal(2);
						platformFund.totalReplay = rst.getBigDecimal(3);
						platformFund.updateTime = rst.getTimestamp(4);
					}
				}
			}
		}
		return platformFund;
	}

	public PagingResult<PtzjglRecord> search(PtzjglRecordQuery query, Paging paging) throws Throwable {
		StringBuilder sql = new StringBuilder(
				"SELECT T7014.F03, T7014.F02, T7014.F04, T7014.F05,T7014.F06,T7014.F07,T6010.F02 AS USERNAME,T6011.F02 xm FROM T7014 LEFT JOIN "
						+ ConsoleConst.DB_USER + ".T6010 ON T7014.F09=T6010.F01 " + "LEFT JOIN " + ConsoleConst.DB_USER
						+ ".T6011 ON T7014.F09=T6011.F01 WHERE 1=1");
		ArrayList<Object> parameters = new ArrayList<>();
		if (query != null) {
			PlatformFundType type = query.getType();
			if (type != null) {
				sql.append(" AND T7014.F02= ?");
				parameters.add(type);
			}
			String userName = query.getUserName();
			if (!StringHelper.isEmpty(userName)) {
				sql.append(" AND T6010.F02 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(userName));
			}
			String xm = query.getXm();
			if (!StringHelper.isEmpty(xm)) {
				sql.append(" AND T6011.F02 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(xm));
			}
			Timestamp date = query.getStartPayTime();
			if (date != null) {
				sql.append(" AND DATE(T7014.F03) >=?");
				parameters.add(date);
			}
			date = query.getEndPayTime();
			if (date != null) {
				sql.append(" AND DATE(T7014.F03) <=?");
				parameters.add(date);
			}
		}
		sql.append(" ORDER BY T7014.F03 DESC");
		return selectPaging(getConnection(ConsoleConst.DB_CONSOLE), new ArrayParser<PtzjglRecord>() {
			ArrayList<PtzjglRecord> list = new ArrayList<PtzjglRecord>();

			public PtzjglRecord[] parse(ResultSet rst) throws SQLException {
				while (rst.next()) {
					PtzjglRecord platform = new PtzjglRecord();
					platform.playTime = rst.getTimestamp(1);
					platform.type = EnumParser.parse(PlatformFundType.class, rst.getString(2));
					platform.income = rst.getBigDecimal(3);
					platform.replay = rst.getBigDecimal(4);
					platform.remain = rst.getBigDecimal(5);
					platform.remark = rst.getString(6);
					platform.loginName = rst.getString(7);
					platform.xm = rst.getString(8);
					list.add(platform);
				}
				return list.toArray(new PtzjglRecord[list.size()]);
			}
		}, paging, sql.toString(), parameters);
	}

	@Override
	public PagingResult<Ptzjgl> searchXlb(int bid, Paging paging) throws Throwable {
		ArrayList<Object> parameters = new ArrayList<>();
		StringBuilder sql = new StringBuilder(
				"SELECT T7015.F01 bid, T7015.F02 ze, T7015.F03 sr,T7015.F04 zc,T6013.F02 ywm,T6013.F04 zwm FROM T7015 LEFT JOIN "
						+ ConsoleConst.DB_USER + ".T6013 ON T6013.F01=T7015.F01 WHERE 1=1");
		if (bid > 0) {
			sql.append(" AND T7015.F01=?");
			parameters.add(bid);
		}
		return selectPaging(getConnection(ConsoleConst.DB_CONSOLE), new ArrayParser<Ptzjgl>() {
			ArrayList<Ptzjgl> list = new ArrayList<Ptzjgl>();

			public Ptzjgl[] parse(ResultSet rst) throws SQLException {
				while (rst.next()) {
					Ptzjgl platformFund = new Ptzjgl();
					platformFund.bid = rst.getInt(1);
					platformFund.platformAmount = rst.getBigDecimal(2);
					platformFund.totalIncome = rst.getBigDecimal(3);
					platformFund.totalReplay = rst.getBigDecimal(4);
					platformFund.b_ywm = rst.getString(5);
					platformFund.b_zwm = rst.getString(6);
					list.add(platformFund);
				}
				return list.toArray(new Ptzjgl[list.size()]);
			}
		}, paging, sql.toString(), parameters);
	}
	
	@Override
	public PagingResult<Ptzjgl> searchXlbSy(int bid, Paging paging) throws Throwable {
		ArrayList<Object> parameters = new ArrayList<>();
		StringBuilder sql = new StringBuilder("SELECT T6013.F01 bid,T6013.F02 ywm,T6013.F04 zwm ,SUM(T7016.F05) zsr,SUM(T7016.F06) zxc");
		sql.append(" FROM "+P2PConst.DB_USER+".T6013");
		sql.append(" LEFT JOIN T7016 ON T6013.F01=T7016.F02"); 
		sql.append(" LEFT JOIN "+P2PConst.DB_USER+".T6010 ON T7016.F10=T6010.F01");
		sql.append(" WHERE T6010.F12=?");  
		parameters.add(IsPass.F);
		if (bid > 0) {
			sql.append(" AND T6013.F01=?");
			parameters.add(bid);
		}
		sql.append(" GROUP BY T6013.F01");
		return selectPaging(getConnection(ConsoleConst.DB_CONSOLE), new ArrayParser<Ptzjgl>() {
			ArrayList<Ptzjgl> list = new ArrayList<Ptzjgl>();

			public Ptzjgl[] parse(ResultSet rst) throws SQLException {
				while (rst.next()) {
					Ptzjgl platformFund = new Ptzjgl();
					platformFund.bid = rst.getInt(1);
					platformFund.b_ywm = rst.getString(2);
					platformFund.b_zwm = rst.getString(3);
					platformFund.totalIncome = rst.getBigDecimal(4);
					platformFund.totalReplay = rst.getBigDecimal(5);
					platformFund.jrtotalIncome =selectBigDecimal(getConnection(P2PConst.DB_CONSOLE), "SELECT SUM(T7016.F05) FROM T7016 WHERE F02=? AND DATE(T7016.F04)=DATE(NOW())", platformFund.bid);
					platformFund.jrtotalReplay =selectBigDecimal(getConnection(P2PConst.DB_CONSOLE), "SELECT SUM(T7016.F06) FROM T7016 WHERE F02=? AND DATE(T7016.F04)<=DATE(NOW())", platformFund.bid);
					list.add(platformFund);
				}
				return list.toArray(new Ptzjgl[list.size()]);
			}
		}, paging, sql.toString(), parameters);
	}
			
	

		
	@Override
	public PagingResult<PtzjglRecord> searchJyjl(int bid, PtzjglRecordQuery query, Paging paging) throws Throwable {
		if (bid <= 0) {
			if (bid <= 0) {
				throw new ParameterException("ID异常。");
			}
		}
		StringBuilder sql = new StringBuilder("SELECT T7016.F04, T7016.F03, T7016.F05, T7016.F06,T7016.F07,T7016.F09,");
		sql.append(" T6010.F02 AS USERNAME,T6011.F02 xm,T6013.F02 ywm,T6013.F04 zwm");
		sql.append(" FROM T7016 LEFT JOIN " + ConsoleConst.DB_USER + ".T6010 ON T7016.F10=T6010.F01");
		sql.append(" LEFT JOIN " + ConsoleConst.DB_USER + ".T6011 ON T7016.F10=T6011.F01");
		sql.append(" LEFT JOIN " + ConsoleConst.DB_USER + ".T6013 ON T7016.F02=T6013.F01");
		sql.append(" WHERE 1=1");
		ArrayList<Object> parameters = new ArrayList<>();
		if (query != null) {
			PtXlbType type = query.getPtXlbType();
			if (type != null) {
				sql.append(" AND T7016.F03= ?");
				parameters.add(type);
			}
			String userName = query.getUserName();
			if (!StringHelper.isEmpty(userName)) {
				sql.append(" AND T6010.F02 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(userName));
			}
			String xm = query.getXm();
			if (!StringHelper.isEmpty(xm)) {
				sql.append(" AND T6011.F02 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(xm));
			}
			Timestamp date = query.getStartPayTime();
			if (date != null) {
				sql.append(" AND DATE(T7016.F04) >=?");
				parameters.add(date);
			}
			date = query.getEndPayTime();
			if (date != null) {
				sql.append(" AND DATE(T7016.F04) <=?");
				parameters.add(date);
			}
		}
		sql.append(" AND T7016.F02=?");
		parameters.add(bid);
		sql.append(" ORDER BY T7016.F04 DESC");
		return selectPaging(getConnection(ConsoleConst.DB_CONSOLE), new ArrayParser<PtzjglRecord>() {
			ArrayList<PtzjglRecord> list = new ArrayList<PtzjglRecord>();

			public PtzjglRecord[] parse(ResultSet rst) throws SQLException {
				while (rst.next()) {
					PtzjglRecord platform = new PtzjglRecord();
					platform.playTime = rst.getTimestamp(1);
					platform.ptXlbType = EnumParser.parse(PtXlbType.class, rst.getString(2));
					platform.income = rst.getBigDecimal(3);
					platform.replay = rst.getBigDecimal(4);
					platform.remain = rst.getBigDecimal(5);
					platform.remark = rst.getString(6);
					platform.loginName = rst.getString(7);
					platform.xm = rst.getString(8);
					platform.b_ywm = rst.getString(9);
					platform.b_zwm = rst.getString(10);
					list.add(platform);
				}
				return list.toArray(new PtzjglRecord[list.size()]);
			}
		}, paging, sql.toString(), parameters);
	}

	@Override
	public PagingResult<TtQbEntity> searchPtqb(Paging paging) throws Throwable {
		StringBuilder s = new StringBuilder(
				"SELECT T7103.F03 dz,T7103.F04 sy,T6013.F03 jc,T6013.F04 zwm,T6013.F01 bid,T7103.F05,T7103.F06,T7103.F07,T7103.F08 FROM T7103 LEFT JOIN "
						+ P2PConst.DB_USER + ".T6013 ON T7103.F02=T6013.F01");
		return selectPaging(getConnection(ConsoleConst.DB_CONSOLE), new ArrayParser<TtQbEntity>() {
			ArrayList<TtQbEntity> list = new ArrayList<TtQbEntity>();

			@Override
			public TtQbEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					TtQbEntity t = new TtQbEntity();
					t.dz = re.getString(1);
					t.sy = re.getString(2);
					t.jc = re.getString(3);
					t.zwm = re.getString(4);
					t.bid = re.getInt(5);
					t.ip = re.getString(6);
					t.prot = re.getString(7);
					t.username = re.getString(8);
					t.pass = re.getString(9);
					
					String coinType =  selectString(P2PConst.DB_USER, "SELECT F26 FROM T6013 WHERE F01=?", t.bid);
					if (CoinType.SWT.name().equals(coinType)) {
						if("TCC".equals(t.jc)){
							t.jc="6CAB220FC47B66486AC27F3A91A0BA5A6003A860";
						}
						String ip = selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", t.bid);// IP
						t.ye = String.valueOf(BtcUtil.getSwtYe(t.jc, t.dz, ip));
					}
					if (CoinType.BTC.name().equals(coinType)) {
						t.ye = String.valueOf(BtcUtil.getBtcYe(t.ip, t.prot, t.username, t.pass));
					}

					if (CoinType.NEO.name().equals(coinType)) {
						String contractAddress = selectString(P2PConst.DB_USER, "SELECT F24 FROM T6013 WHERE F01=?", t.bid);
						try {
							t.ye = NEOUtil.getBalance(t.ip, t.prot, contractAddress).toString();
						} catch (Throwable e) {
							t.ye = "获取失败";
							e.printStackTrace();
						}
					}
					
					if(CoinType.ETH.toString().equals(coinType)){
						String contractAddress = selectString(P2PConst.DB_USER, "SELECT F24 FROM T6013 WHERE F01=?", t.bid);
						String unit = selectString(P2PConst.DB_USER, "SELECT F25 FROM T6013 WHERE F01=?", t.bid);
						try {
							if (t.jc.toUpperCase().equals("ETH")) {
								t.ye = EthereumUtil.eth_getBalance(t.ip, t.prot, t.username).toString();
							}else{
								t.ye = EthereumUtil.contract_getBalance(t.ip, t.prot, contractAddress, t.username, unit).toString();
							}
						} catch (Throwable e) {
							t.ye = "获取失败";
							e.printStackTrace();
						}
					}
					list.add(t);
				}

				return list.toArray(new TtQbEntity[list.size()]);
			}
		}, paging, s.toString());
	}
	
	@Override
	public void addQb(int bid, String qbdz, String sy, String ip, String prot, String username, String password)
			throws Throwable {
		if (bid <= 0) {
			throw new ParameterException("币ID不能小于0。");
		}
		/*
		 * if (StringHelper.isEmpty(qbdz)) { throw new
		 * ParameterException("钱包地址不能为空。"); } if (StringHelper.isEmpty(sy)) {
		 * throw new ParameterException("私钥不能为空。"); }
		 */
		int count = selectInt(getConnection(ConsoleConst.DB_CONSOLE), "SELECT COUNT(F01) FROM T7103 WHERE F02=?", bid);
		if (count > 0) {
			throw new ParameterException("已添加地址，请勿重复添加。");
		}
		if (!StringHelper.isEmpty(sy)) {
			sy = MyCrypt.myEncode(sy);
		}
//		if (!StringHelper.isEmpty(password)) {
//			password = MyCrypt.myEncode(password);
//		}
		execute(getConnection(ConsoleConst.DB_CONSOLE),
				"INSERT INTO T7103 SET F02=?,F03=?,F04=?,F05=?,F06=?,F07=?,F08=?", bid, qbdz, sy, ip, prot, username,
				password);
	}
}
